package com.salt.admin.api.feign.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 公共拦截器，处理feign远程调用过滤token问题
 * @Author salt
 * @Date 2020-11-12
 * @Version 1.0.1
 */
@Configuration
public class FeignTokenInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        if (null == requestTemplate) return;
        if (null != getHttpServletRequest()) {
            requestTemplate.header("token", getHttpServletRequest().getHeader("token"));
        }
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

}
